package tsli.acm.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import tsli.acm.biz.AgentDebtManagement;
import tsli.acm.dao.GACommissionPositiveDAO;
import tsli.acm.database.Database;

/**
 * Servlet implementation class ACM1301Srvl
 */
@WebServlet("/ACM1301Srvl")
public class ACM1301Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ACM1301Srvl() {
        super();
        // TODO Auto-generated constructor stub
    }

    public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");
		if (request.getParameter("process_type").equals("getDataTable")) {
			getDataTable(request, response);
		} else if (request.getParameter("process_type").equals("showData")) {
			showData(request, response);
		} 

	}

	
	@SuppressWarnings("unchecked")
	public void getDataTable(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String paAgentNo = request.getParameter("sSearch_0").trim();
		String paCalculationType = request.getParameter("sSearch_1").trim();
		String paQuarterly = request.getParameter("sSearch_2").trim();
		String paYear = request.getParameter("sSearch_3").trim();
		String paMonth1 = "";
		String paMonth2 = "";
		String paMonth3 = "";
		
		if (paAgentNo.equals("")) {
			paAgentNo = "%";
		}
		if (paQuarterly.equals("1")) {
			paMonth1 = paYear + "01";
			paMonth2 = paYear + "02";
			paMonth3 = paYear + "03";
		} else if (paQuarterly.equals("2")) {
			paMonth1 = paYear + "04";
			paMonth2 = paYear + "05";
			paMonth3 = paYear + "06";
		} else if (paQuarterly.equals("3")) {
			paMonth1 = paYear + "07";
			paMonth2 = paYear + "08";
			paMonth3 = paYear + "09";
		} else if (paQuarterly.equals("4")) {
			paMonth1 = paYear + "10";
			paMonth2 = paYear + "10";
			paMonth3 = paYear + "11";
		}
		String paPersistencyCategory = "S11030B10507";
		Database db = new Database();
		GACommissionPositiveDAO voGACommissionPositiveDAO = new GACommissionPositiveDAO(
				db);
		List<Map<String, Object>> voAgPcList = null;
		if (paCalculationType.equals("quarter")) {
			voAgPcList = voGACommissionPositiveDAO.getAllPcByQuarterly(
					paAgentNo, paMonth1, paMonth2, paMonth3,
					paPersistencyCategory);

		} else {
			voAgPcList = voGACommissionPositiveDAO.getAllPcByAnnual(paAgentNo,
					paYear, paPersistencyCategory);

		}
		double vnPc = 0;
		double vnBonusRate = 0;
		double vnBonus = 0;
		double vnPersistencyCredit = 0;
		double vnPersistencyRate = 0;
		int vnExperience = 0;
		double vnQuarterlySumBonus = 0;
		double vnAnnualBonus = 0;
		String vaAgentNo = null;
		String vaAgentName = null;
		DecimalFormat df = new DecimalFormat("#,##0.00");
		PrintWriter voOut = response.getWriter();
		JSONObject voObject = new JSONObject();
		JSONArray voListData = new JSONArray();

		int size = 0;
		if (voAgPcList != null) {
			size = voAgPcList.size();
		}
		for (int i = 0; i < size; i++) {
			vnPc = 0;
			vnBonusRate = 0;
			vnBonus = 0;
			vnPersistencyCredit = 0;
			vnPersistencyRate = 0;
			vnExperience = 0;
			vnQuarterlySumBonus = 0;
			vnAnnualBonus = 0;
			vaAgentNo = voAgPcList.get(i).get("PE_NO_COL").toString();
			vaAgentName = voGACommissionPositiveDAO.findNameById(vaAgentNo);

			vnPc = Double.parseDouble(voAgPcList.get(i).get("PC").toString());
			if (paCalculationType.equals("quarter")) {
				if (Math.abs(vnPc) >= 0 && Math.abs(vnPc) <= 44999) {
					vnBonusRate = 0;
				} else if (Math.abs(vnPc) >= 45000 && Math.abs(vnPc) <= 69999) {
					vnBonusRate = 0.06;
				} else if (Math.abs(vnPc) >= 70000 && Math.abs(vnPc) <= 119999) {
					vnBonusRate = 0.07;
				} else if (Math.abs(vnPc) >= 120000 && Math.abs(vnPc) <= 179999) {
					vnBonusRate = 0.08;
				} else if (Math.abs(vnPc) >= 180000 && Math.abs(vnPc) <= 249999) {
					vnBonusRate = 0.09;
				} else if (Math.abs(vnPc) >= 250000 && Math.abs(vnPc) <= 349999) {
					vnBonusRate = 0.10;
				} else if (Math.abs(vnPc) >= 350000 && Math.abs(vnPc) <= 549999) {
					vnBonusRate = 0.11;
				} else {
					vnBonusRate = 0.12;
				}
			}else{
				if (Math.abs(vnPc) >= 0 && Math.abs(vnPc) <= 179999) {
					vnBonusRate = 0;
				} else if (Math.abs(vnPc) >= 180000 && Math.abs(vnPc) <= 279999) {
					vnBonusRate = 0.06;
				} else if (Math.abs(vnPc) >= 280000 && Math.abs(vnPc) <= 479999) {
					vnBonusRate = 0.07;
				} else if (Math.abs(vnPc) >= 480000 && Math.abs(vnPc) <= 719999) {
					vnBonusRate = 0.08;
				} else if (Math.abs(vnPc) >= 720000 && Math.abs(vnPc) <= 999999) {
					vnBonusRate = 0.09;
				} else if (Math.abs(vnPc) >= 1000000 && Math.abs(vnPc) <= 1399999) {
					vnBonusRate = 0.10;
				} else if (Math.abs(vnPc) >= 1400000 && Math.abs(vnPc) <= 2199999) {
					vnBonusRate = 0.11;
				} else {
					vnBonusRate = 0.12;
				}
			}
			
			String ckPersistencyCredit = "";
			if (paCalculationType.equals("quarter")) {
				if (voGACommissionPositiveDAO.getPersistencyCreditByQuarterly(
						vaAgentNo, paMonth3, paPersistencyCategory) == null) {
					ckPersistencyCredit = "T";
				} else {
					vnPersistencyRate = Double
							.parseDouble(voGACommissionPositiveDAO
									.getPersistencyCreditByQuarterly(vaAgentNo,
											paMonth3, paPersistencyCategory)
									.get("PRST_RTE").toString());
				}
			} else {
				if (voGACommissionPositiveDAO.getPersistencyCreditByAnnual(
						vaAgentNo, paYear, paPersistencyCategory) == null) {
					ckPersistencyCredit = "T";
				} else {
					vnPersistencyRate = Double
							.parseDouble(voGACommissionPositiveDAO
									.getPersistencyCreditByAnnual(vaAgentNo,
											paYear, paPersistencyCategory)
									.get("PRST_RTE").toString());
				}
			}

			if (vnPersistencyRate >= 0 && vnPersistencyRate <= 59.99) {
				vnPersistencyCredit = 0;
			} else if (vnPersistencyRate >= 60 && vnPersistencyRate <= 74.99) {
				vnPersistencyCredit = 0.5;
			} else if (vnPersistencyRate >= 75 && vnPersistencyRate <= 79.99) {
				vnPersistencyCredit = 0.9;
			} else if (vnPersistencyRate >= 80 && vnPersistencyRate <= 84.99) {
				vnPersistencyCredit = 1;
			} else if (vnPersistencyRate >= 85 && vnPersistencyRate <= 89.99) {
				vnPersistencyCredit = 1.1;
			} else {
				vnPersistencyCredit = 1.2;
			}
			if (paCalculationType.equals("quarter")) {
				vnExperience = Integer.parseInt(voGACommissionPositiveDAO
						.getExperienceByQuarterly(vaAgentNo, paMonth3)
						.get("FST_ENCO_MMS").toString());
			} else {
				vnExperience = Integer.parseInt(voGACommissionPositiveDAO
						.getExperienceByAnnual(vaAgentNo, paYear)
						.get("FST_ENCO_MMS").toString());

			}
			
			if (ckPersistencyCredit.equals("T")) { // สำหรับตัวแทนทุกท่านที่ยังไม่มีอัตราความยั่งยืน
				vnPersistencyCredit = 1.00;
				

			}
			if (vnExperience > 0 && vnExperience <= 13
					&& vnPersistencyCredit >= 1) { // สำหรับตัวแทนใหม่ อายุงาน 1
													// - 13 เดือน
													// ทุกท่านที่มีอัตราความยั่งยืนมากกว่าหรือเท่ากับ
													// 80%

				vnPersistencyCredit = 1.00;

			}
			
			vnBonus = (vnPc * vnBonusRate * vnPersistencyCredit);
			
			String voCalculateQuarterly1[] = new String[3];
			String voCalculateQuarterly2[] = new String[3];
			String voCalculateQuarterly3[] = new String[3] ;
			String voCalculateQuarterly4[] = new String[3];
			
			if (paCalculationType.equals("annual")) {
				voCalculateQuarterly1 = calculateQuarterly(db, vaAgentNo,
						"1", paYear);
				voCalculateQuarterly2 = calculateQuarterly(db, vaAgentNo,
						"2", paYear);
				voCalculateQuarterly3 = calculateQuarterly(db, vaAgentNo,
						"3", paYear);
				voCalculateQuarterly4 = calculateQuarterly(db, vaAgentNo,
						"4", paYear);

				double vnBonus1 = Double.parseDouble(voCalculateQuarterly1[0]);
				double vnBonus2 = Double.parseDouble(voCalculateQuarterly2[0]);
				double vnBonus3 = Double.parseDouble(voCalculateQuarterly3[0]);
				double vnBonus4 = Double.parseDouble(voCalculateQuarterly4[0]);
				vnQuarterlySumBonus = vnBonus1 + vnBonus2 + vnBonus3 + vnBonus4;
				vnAnnualBonus = vnBonus;
				if(vnQuarterlySumBonus >=0){
					vnBonus = vnBonus - vnQuarterlySumBonus;
				}else{
					vnBonus = vnBonus + vnQuarterlySumBonus;
				}
				
			}
			if (vnBonus > 0) {
				if (paCalculationType.equals("annual")) {
					if (voCalculateQuarterly1[2].equals("false")
							|| voCalculateQuarterly2[2].equals("false")
							|| voCalculateQuarterly3[2].equals("false")
							|| voCalculateQuarterly4[2].equals("false")) {
						vnBonus = vnBonus * 0.8;
						if(vnQuarterlySumBonus >=0){
							vnBonus = (vnAnnualBonus*0.8)-vnQuarterlySumBonus;
						}else{
							vnBonus = (vnAnnualBonus*0.8)+vnQuarterlySumBonus;
						}
					}

				} else {
					
					if (ckPersistencyCredit.equals("T")) { // สำหรับตัวแทนทุกท่านที่ยังไม่มีอัตราความยั่งยืน
						vnBonus = vnBonus * 0.8;
					}
				}
			} 
			AgentDebtManagement voAgentDebtManagement = new AgentDebtManagement();
			double voBonus[] = { vnBonus };

			String[] vaResult = voAgentDebtManagement.CalAgentDebt(vaAgentNo, voBonus, db);
			double vnDept =0;
		
				vnDept = vnBonus - Double.parseDouble(vaResult[0]);
			
			JSONArray voArray = new JSONArray();
			JSONArray voData = new JSONArray();
			
			voArray.add(i + 1);
			voArray.add(vaAgentNo);
			voArray.add(vaAgentName);
			voArray.add(df.format(vnBonus));
			voArray.add(df.format(vnBonus-vnDept));
			voData.add(vaAgentNo);
			voData.add(vnBonus);
			voData.add(vaResult[2]);
			voArray.add(voData);
			voListData.add(voArray);

		}

		voObject.put("aaData", voListData);
		voOut.print(voObject.toJSONString());

	}

	public String[] calculateQuarterly(Database db, String paAgentNo,
			String paQuarterly, String paYear) {

		String paMonth1 = "";
		String paMonth2 = "";
		String paMonth3 = "";
		String vaBonus100 = "true";
		String data[] = new String[3];
	
		if (paQuarterly.equals("1")) {
			paMonth1 = paYear + "01";
			paMonth2 = paYear + "02";
			paMonth3 = paYear + "03";
		} else if (paQuarterly.equals("2")) {
			paMonth1 = paYear + "04";
			paMonth2 = paYear + "05";
			paMonth3 = paYear + "06";
		} else if (paQuarterly.equals("3")) {
			paMonth1 = paYear + "07";
			paMonth2 = paYear + "08";
			paMonth3 = paYear + "09";
		} else if (paQuarterly.equals("4")) {
			paMonth1 = paYear + "10";
			paMonth2 = paYear + "10";
			paMonth3 = paYear + "11";
		}
		String paPersistencyCategory = "S11030B10507";
		// Database db = new Database();
		GACommissionPositiveDAO voGACommissionPositiveDAO = new GACommissionPositiveDAO(
				db);
		List<Map<String, Object>> voAgPcList = voGACommissionPositiveDAO
				.getAllPcByQuarterly(paAgentNo, paMonth1, paMonth2, paMonth3,
						paPersistencyCategory);

		double vnPc = 0;
		double vnBonusRate = 0;
		double vnBonus = 0;
		double vnBonus80 = 0;
		double vnBonus20 = 0;
		double vnPersistencyCredit = 0;
		double vnPersistencyRate = 0;
		int vnExperience = 0;
		String vaAgentNo = null;

		int size = 0;
		if (voAgPcList != null) {
			size = voAgPcList.size();
		}
		for (int i = 0; i < size; i++) {
			vnPc = 0;
			vnBonusRate = 0;
			vnBonus = 0;
			vnPersistencyCredit = 0;
			vnPersistencyRate = 0;
			vnExperience = 0;
			vaAgentNo = voAgPcList.get(i).get("PE_NO_COL").toString();

			vnPc = Double.parseDouble(voAgPcList.get(i).get("PC").toString());

			if (Math.abs(vnPc) >= 0 && Math.abs(vnPc) <= 44999) {
				vnBonusRate = 0;
			} else if (Math.abs(vnPc) >= 45000 && Math.abs(vnPc) <= 69999) {
				vnBonusRate = 0.06;
			} else if (Math.abs(vnPc) >= 70000 && Math.abs(vnPc) <= 119999) {
				vnBonusRate = 0.07;
			} else if (Math.abs(vnPc) >= 120000 && Math.abs(vnPc) <= 179999) {
				vnBonusRate = 0.08;
			} else if (Math.abs(vnPc) >= 180000 && Math.abs(vnPc) <= 249999) {
				vnBonusRate = 0.09;
			} else if (Math.abs(vnPc) >= 250000 && Math.abs(vnPc) <= 349999) {
				vnBonusRate = 0.10;
			} else if (Math.abs(vnPc) >= 350000 && Math.abs(vnPc) <= 549999) {
				vnBonusRate = 0.11;
			} else {
				vnBonusRate = 0.12;
			}
			String ckPersistencyCredit = "";
			if (voGACommissionPositiveDAO.getPersistencyCreditByQuarterly(
					vaAgentNo, paMonth3, paPersistencyCategory) == null) {
				ckPersistencyCredit = "T";
			} else {
				vnPersistencyRate = Double
						.parseDouble(voGACommissionPositiveDAO
								.getPersistencyCreditByQuarterly(vaAgentNo,
										paMonth3, paPersistencyCategory)
								.get("PRST_RTE").toString());
			}

			if (vnPersistencyRate >= 0 && vnPersistencyRate <= 59.99) {
				vnPersistencyCredit = 0;
			} else if (vnPersistencyRate >= 60 && vnPersistencyRate <= 74.99) {
				vnPersistencyCredit = 0.5;
			} else if (vnPersistencyRate >= 75 && vnPersistencyRate <= 79.99) {
				vnPersistencyCredit = 0.9;
			} else if (vnPersistencyRate >= 80 && vnPersistencyRate <= 84.99) {
				vnPersistencyCredit = 1;
			} else if (vnPersistencyRate >= 85 && vnPersistencyRate <= 89.99) {
				vnPersistencyCredit = 1.1;
			} else {
				vnPersistencyCredit = 1.2;
			}
			vnExperience = Integer.parseInt(voGACommissionPositiveDAO
					.getExperienceByQuarterly(vaAgentNo, paMonth3)
					.get("FST_ENCO_MMS").toString());
			
			if (ckPersistencyCredit.equals("T")) { // สำหรับตัวแทนทุกท่านที่ยังไม่มีอัตราความยั่งยืน
				vnPersistencyCredit = 1.00;
				

			}
			if (vnExperience > 0 && vnExperience <= 13
					&& vnPersistencyCredit >= 1) { // สำหรับตัวแทนใหม่ อายุงาน 1
													// - 13 เดือน
													// ทุกท่านที่มีอัตราความยั่งยืนมากกว่าหรือเท่ากับ
													// 80%

				vnPersistencyCredit = 1.00;

			}
			
			vnBonus = (vnPc * vnBonusRate * vnPersistencyCredit);

			
			if (vnBonus > 0) {
				if (ckPersistencyCredit.equals("T")) { // สำหรับตัวแทนทุกท่านที่ยังไม่มีอัตราความยั่งยืน
					vnBonus80 = vnBonus * 0.8;
					vnBonus20 = vnBonus * 0.2;
					vnBonus = vnBonus80;
					vaBonus100 = "false";
				}
			}

		}
		data[0] = "" + vnBonus;
		data[1] = "" + vnBonus20;
		data[2] = "" + vaBonus100;

		// db.close();
		return data;
	}

	@SuppressWarnings("unchecked")
	public void showData(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String vaAgentNo = request.getParameter("agent_number");
		String vaBonus = request.getParameter("bonus");
		Database db = new Database();
		PrintWriter out = response.getWriter();
		JSONObject voObject = new JSONObject();			
		AgentDebtManagement voAgentDebtManagement = new AgentDebtManagement();
		double voBonus[] = { Double.parseDouble(vaBonus) };
		DecimalFormat df = new DecimalFormat("#,##0.00");
		String[] vaResult = voAgentDebtManagement.CalAgentDebt(vaAgentNo, voBonus, db);
         String vaAgentDebt = df.format(Double.parseDouble(vaResult[0]));
		 String vaMessage = vaResult[1];
		 
		voObject.put("AgentDebt", vaAgentDebt);
		voObject.put("Message", vaMessage);
		out.print(voObject.toJSONString());
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
